package utils

import org.apache.commons.io.FileUtils
import play.api.libs.json.Json
import shapeless.{HList, LabelledGeneric, Lazy}
import tool.Tool

import java.io.File
import scala.concurrent.{Await, Future}
import scala.concurrent.duration.Duration
import implicits.Implicits._

/**
 * Created by yz on 13/12/2021
 */
object Utils {

  def isWindows = {
    System.getProperty("os.name") match {
      case x if x.contains("Windows") => true
      case _ => false
    }
  }

  def getTime(startTime: Long) = {
    val endTime = System.currentTimeMillis()
    (endTime - startTime) / 1000.0
  }

  def getArrayByTs[T, H <: HList](x: Seq[T])(implicit generic: LabelledGeneric.Aux[T, H],
                                             hc: Lazy[ObjectCodec[H]]) = {
    x.map { y =>
      y.myAsJson
    }
  }

  def deleteDirectory(direcotry: File) = {
    try {
      FileUtils.deleteDirectory(direcotry)
    } catch {
      case _ =>
    }
  }

  def execFuture[T](f: Future[T]): T = {
    Await.result(f, Duration.Inf)
  }

  def t2ConfigFile[T, H <: HList](data: T, configFile: File)(implicit generic: LabelledGeneric.Aux[T, H],
                                                             hc: Lazy[ObjectCodec[H]]

  ): File = {
    val json = data.myAsJson
    Json.stringify(json).toFile(configFile)
  }

  def configFile2JsonByFile(configFile: File) = {
    Json.parse(configFile.str)
  }

  def getJsonByTs[T, H <: HList](x: Seq[T])(implicit  generic: LabelledGeneric.Aux[T, H],
                                            hc: Lazy[ObjectCodec[H]]) = {
    val array = getArrayByTs(x)
    Json.toJson(array)
  }

}
